var $ = getApp()
module.exports = {
	onLoad:function(){
		this.setData({platform : $.platform,mid:$.mid,aid:$.aid,pre_url:$.pre_url,indexurl:$.indexurl,textset:$.textset});
		this._onLoad && this._onLoad();
		this.inittabbar();
	},
	inittabbar:function(){
		var that = this
		if($.tabBarData){
			that.setData({tabBarData : $.tabBarData,indexurl:$.indexurl,textset:$.textset});
			that.settabbar();
		}else{
			$.post('index/gettabbardata',{fromw7:$.config.fromw7},function(res){
				that.setData({tabBarData : res.data,indexurl:res.indexurl,textset:res.textset});
				$.tabBarData = res.data
				$.indexurl = res.indexurl
				$.textset = res.textset
				$.menu2data = res.menu2data
				//$.accounttype = res.accounttype
				//that.setData({accounttype:res.accounttype})
				that.settabbar();
			},false)
		}
	},
	settabbar:function(){
		var that = this
		var thispage = $.getpage();
		//console.log(thispage)
		var currenturl  = '/'+ (thispage.route ? thispage.route : thispage.__route__);
		//console.log(currenturl)
		//console.log('------------------')
		if(thispage.options && thispage.options.id){
			currenturl+='?id='+thispage.options.id
		}else if(thispage.options && thispage.options.gid){
			currenturl+='?gid='+thispage.options.gid
		}else if(thispage.options && thispage.options.bid){
			currenturl+='?bid='+thispage.options.bid
		}
		//console.log(thispage)
		var currentIndex = -1;
		var hastabbar = false;
		var tabBarData = this.data.tabBarData;
		var tablist = tabBarData['list'];
		for(var i=0;i<tablist.length;i++){
			if(tablist[i]['pagePath'] == currenturl){
				currentIndex = i;
				hastabbar = true;
				tabBarData['list'][i].color = tabBarData['selectedColor']
			}else{
				tabBarData['list'][i].color = tabBarData['color']
			}
		}
		$.menuIndex = currentIndex;
		if(hastabbar == false){
			var menu2data = $.menu2data
			if(menu2data.length > 0){
				for(var i in menu2data){
					if(menu2data[i].indexurl == currenturl){
						hastabbar = true;
						currentIndex = 10;
						tabBarData = menu2data[i]
					}
				}
			}
		}
		that.setData({currentIndex:currentIndex,hastabbar:hastabbar,tabBarData:tabBarData})
	},
	goto: function (e) {
		//console.log(e)
		var url = e.currentTarget.dataset.url;
		var opentype = e.currentTarget.dataset.opentype
		$.goto(url,opentype);
	},
	goback: function () {
		wx.navigateBack({fail:function(){
			$.goto($.indexurl)
		}});
	},
	searchgoto: function (e) {
    console.log('search444')
		var url = e.currentTarget.dataset.url;
		if (url.indexOf('?') > 0) {
			url += '&keyword='+e.detail.value;
		}else{
			url += '?keyword='+e.detail.value;
		}
		var opentype = e.currentTarget.dataset.opentype
		$.goto(url,opentype);
	},
	previewImage: function (e) {
		var imgurl = e.currentTarget.dataset.url
		var imgurls = e.currentTarget.dataset.urls
		if (!imgurls) imgurls = imgurl;
		if (typeof (imgurls) == 'string') imgurls = imgurls.split(',');
		wx.previewImage({
			current: imgurl, // 当前显示图片的http链接
			urls: imgurls // 需要预览的图片http链接列表
		})
	},
	phone:function(e) {
		var phone = e.currentTarget.dataset.phone;
		wx.makePhoneCall({
			phoneNumber: phone,
			fail: function () {

			}
		});
	},
	program: function (e) {
		var data = e.currentTarget.dataset.data;
		data = data.split(",");
		wx.navigateToMiniProgram({
			appId: data[0],
			path: data[1],
			envVersion: 'release',
			complete: function() {
				//console.log(data[1]);
			}
		});
	},
	subscribeMessage:function(callback){
			var that = this;
			var tmplids = that.data.tmplids;
			if(tmplids && tmplids.length > 0){
				wx.requestSubscribeMessage({
					tmplIds: tmplids,
					success:function(res) {
						for(var i in tmplids){
							if(res[tmplids[i]] == 'accept'){
								$.post('index/subscribemessage',{tmplid:tmplids[i]},function(){})
							}
						}
						console.log(res)
						typeof callback == "function" && callback();
					},
					fail:function(res){
						console.log(res)
						typeof callback == "function" && callback();
					}
				})
			}else{
				typeof callback == "function" && callback();
			}
	},
	onPullDownRefresh: function () {
		this.onLoad();
		wx.stopPullDownRefresh()
	},
	reLoad: function () {
		this.onLoad();
	},
	onShareAppMessage: function () {
		var thisurl = $._fullurl();
		console.log(thisurl);
		if(this.options.scene){
			var scene = this.options.scene
			var scenes = scene.split('_');
			thisurl += '?scene=' + $.mid + (scenes[1] ? '_' + scenes[1] :'') + (scenes[2] ? '_' + scenes[2] :'');
		}else{
			if (thisurl.indexOf('?') > 0) {
				thisurl += '&scene=' + $.mid
			} else {
				thisurl += '?scene=' + $.mid
			}
		}
		console.log(thisurl);
		var title = '';
		if(this.data.title){
			title = this.data.title;
		}else if(this.data._sysset){
			title = this.data._sysset.name;
		}
		return {
			title: title,
			imageUrl: this.data.sharepic ? this.data.sharepic:'',
			path: thisurl
		}
	},
	onShareTimeline:function(){
		var thisurl = $._fullurl();
		if(this.options.scene){
			var scene = this.options.scene
			var scenes = scene.split('_');
			thisurl += '?scene=' + $.mid + (scenes[1] ? '_' + scenes[1] :'') + (scenes[2] ? '_' + scenes[2] :'');
		}else{
			if (thisurl.indexOf('?') > 0) {
				thisurl += '&scene=' + $.mid
			} else {
				thisurl += '?scene=' + $.mid
			}
		}
		var query = thisurl.split('?')[1];
		var title = '';
		if(this.data.title){
			title = this.data.title;
		}else if(this.data._sysset){
			title = this.data._sysset.name;
		}
		return {
			title: title,
			imageUrl: this.data.sharepic ? this.data.sharepic:'',
			query: query
		}
	},
	menuIndexChange:function(e){
		this.setData({menuIndex:e.detail});
	},
	//授权获取用户信息
	getUserInfo:function(authCanClose){
		//是否可关闭
		if(typeof authCanClose == 'undefined'){
			var authCanClose = true;
		}
		if($.platform == 'wx'){
			this.setData({ needAuth:2,authCanClose:authCanClose})
		}else{
			
		}
	},
	authModalClose:function(){
		this.setData({needAuth:0})		
	},
	//微信授权获取用户信息
	bindGetUserInfo: function(e) {
		var that = this;
		
        var userInfo = {
            avatarUrl:"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
            nickName:"微信用户"
        };
				if(userInfo){
					//console.log("点击允许授权");
					wx.login({success (res1){
							var code = res1.code;
							//pid
							console.log(code);
							$.post('pub/userinfo', { userInfo: userInfo,code:code }, function (res2) {
								if(res2.status == 1){
									$.mid = res.mid;
									that.setData({needAuth:0});
									that.onLoad();
								}else{
									$.alert(res.msg)
								}
							});
						}});

				}else{
					//console.log("用户拒绝授权");
				}
			
	},
	//手机号登录
	tellogin:function(e){
		var that = this
		var formdata = e.detail.value;
		var tel = formdata.tel;
		var code = formdata.code;
		if(tel==''){
			$.alert('请输入手机号码');
			return false;
		}
		if(!(/^1[3456789]\d{9}$/.test(tel))){
			$.alert("手机号码有误，请重填");
			return false;
		}
		if(code==''){
			$.alert('请输入短信验证码');
			return false;
		}
		$.post('Pub/login',formdata,function(res){
			if(res.status==1){
				$.success(res.msg);
				$.mid = res.mid;
				that.setData({needAuth:0});
				that.onLoad();
			}else{
				$.alert(res.msg);
			}
		},'登录中');
	},
	logintelinput:function(e){
		this.setData({logintel:e.detail.value})
	},
	sendsmscode:function(){
		var that = this
		if(that.data.smshqing==1) return;
		that.setData({smshqing:1});
		var tel = that.data.logintel;
		if(tel==''){
			$.alert('请输入手机号码');
			that.setData({smshqing:0});
			return false;
		}
		if(!(/^1[3456789]\d{9}$/.test(tel))){
			$.alert("手机号码有误，请重填");
			that.setData({smshqing:0});
			return false;
		}
		$.post("pub/sendsms",{tel:tel},function(data){
			if(data.status!=1){
				$.alert(data.msg);
			}
		});
		var time = 120;
		var t = setInterval(function() {
			time--;
			if (time < 0) {
				that.setData({sendsmsdjs:'重新获取'})
				that.setData({smshqing:0});
				clearInterval(t);
			} else if (time >= 0) {
				that.setData({sendsmsdjs:time+'秒'})
			}
		}, 1000);
	},
	uploadimg:function(e){
		var that = this;
		var field= e.currentTarget.dataset.field
		var pics = that.data[field]
		if(!pics) pics = [];
		$.chooseImage(function(urls){
			for(var i=0;i<urls.length;i++){
				pics.push(urls[i]);
			}
			var res = {};
			res[field] = pics
			that.setData(res);
		},1)	
	},
	removeimg:function(e){
		var that = this;
		var index= e.currentTarget.dataset.index
		var field= e.currentTarget.dataset.field
		var pics = that.data[field]
		pics.splice(index,1);
		var res = {};
		res[field] = pics
		console.log(res)
		that.setData(res);
	},
	xuanzhuan:function(e){
		var that = this;
		var index= e.currentTarget.dataset.index
		var field= e.currentTarget.dataset.field
		var pics = that.data[field]
		$.post('imageupload/xuanzhuan',{ url:pics[index]},function(res){
			if(res.status==1){
				pics[index] = res.url
			}else{
				$.error(res.msg);
			}
			var res = {};
			res[field] = pics
			that.setData(res);
		});
	},
	getcoupon:function(e){
		var that = this
		var id = e.currentTarget.dataset.id;
		var score = e.currentTarget.dataset.score;
		var price = e.currentTarget.dataset.price;
		if(price > 0){
			$.goto('/pages/wxpay/buycoupon?id='+id);
			return ;
		}
		if(score > 0){
			$.confirm('确定要消耗'+score+''+(that.data.textset['积分'] || '积分')+'兑换吗?',function(){
				$.post('coupon/getcoupon',{id:id},function(data){
					if(data.status==0){
						$.error(data.msg);
					}else{
						$.success(data.msg);
					}
				},'兑换中');
			})
		}else{
			$.post('coupon/getcoupon',{id:id},function(data){
				if(data.status==0){
					$.error(data.msg);
				}else{
					$.success(data.msg);
				}
			},'领取中');
		}
	},
	_bannerchange:function(e){
		var that = this
		var idx = e.currentTarget.dataset.idx
		var currentindex = e.detail.current
		var _bannerindex = that.data._bannerindex
		_bannerindex[idx] = currentindex;
		that.setData({_bannerindex:_bannerindex})
	},
	_editorFormSubmit:function(e){
		var that = this;
		//console.log('form发生了submit事件，携带数据为：', e.detail.value)
		var subdata = e.detail.value;
		var formcontent = e.currentTarget.dataset.formcontent;
		var formid = e.currentTarget.dataset.formid;
		var tourl = e.currentTarget.dataset.tourl;
		var formdata = new Array();
		for (var i = 0; i < formcontent.length;i++){
			//console.log(subdata['form' + i]);
			if (formcontent[i].val3 == 1 && (subdata['form' + i] === '' || subdata['form' + i] === undefined || subdata['form' + i].length==0)){
					$.alert(formcontent[i].val1+' 必填');return;
			}
			if (formcontent[i].key =='switch'){
					if (subdata['form' + i]==false){
							subdata['form' + i] = '否'
					}else{
							subdata['form' + i] = '是'
					}
			}
			if (formcontent[i].key == 'selector') {
					subdata['form' + i] = formcontent[i].val2[subdata['form' + i]]
			}
			formdata.push(subdata['form' + i])
		}
		//console.log(formdata);
		$.post('form/formsubmit', {formid:formid,formdata:subdata,price:subdata.price},function(data){
			if (data.status == 0) {
				//that.showsuccess(res.data.msg);
				setTimeout(function () {
					$.error(data.msg);
				}, 100)
				return;
			}else if(data.status == 1) { //无需付款
				setTimeout(function () {
					$.success(data.msg);
				}, 100)
				setTimeout(function () {
					$.goto(tourl);
				}, 1000)
				return;
			}else if(data.status==2){
				$.goto('/pages/wxpay/formpay?orderid='+data.orderid+'&tourl='+tourl);
			}
		},'提交中');
	},
	_editorChooseImage: function (e) {
		var that = this;
		var idx = e.currentTarget.dataset.idx;
		var tplindex = e.currentTarget.dataset.tplindex;
		var _editorFormdata = this.data._editorFormdata;
		if(!_editorFormdata) _editorFormdata = [];
		if(!_editorFormdata[tplindex]) _editorFormdata[tplindex] = [];
		$.chooseImage(function(data){
			_editorFormdata[tplindex][idx] = data[0];
			//console.log(_editorFormdata);
			that.setData({ _editorFormdata: _editorFormdata})
		})
	},
	_editorBindPickerChange:function(e){
		var idx = e.currentTarget.dataset.idx;
		var tplindex = e.currentTarget.dataset.tplindex;
		var val = e.detail.value;
		var _editorFormdata = this.data._editorFormdata;
		if(!_editorFormdata) _editorFormdata = [];
		if(!_editorFormdata[tplindex]) _editorFormdata[tplindex] = [];
		_editorFormdata[tplindex][idx] = val;
		//console.log(_editorFormdata);
		this.setData({ _editorFormdata: _editorFormdata})
	},
	openLocation:function(e){
		//console.log(e)
		var latitude = parseFloat(e.currentTarget.dataset.latitude)
		var longitude = parseFloat(e.currentTarget.dataset.longitude)
		var address = e.currentTarget.dataset.address
		wx.openLocation({
     latitude:latitude,
     longitude:longitude,
		 name:address,
     scale: 13
   })		
	},
	getDistance: function (lat1, lng1, lat2, lng2) {
		if(!lat1 || !lng1 || !lat2 || !lng2) return '';
		var rad1 = lat1 * Math.PI / 180.0;
		var rad2 = lat2 * Math.PI / 180.0;
		var a = rad1 - rad2;
		var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
		var r = 6378137;
		var juli = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
		juli = juli/1000
		juli = juli.toFixed(2);
		return juli;
	},
	opencard:function(e){
		var cardId = e.currentTarget.dataset.card_id
		var code = e.currentTarget.dataset.card_code
		wx.openCard({
			cardList: [{
				cardId: cardId,
				code: code
			}],
			success:function(res) { }
		})
	},
	//领取卡券
	addcard:function(e){
		var cardId = e.currentTarget.dataset.card_id
		$.post('coupon/getcardext',{card_id:cardId},function(res){
			if(res.status==0){
				$.alert(res.msg);
				return;
			}
			wx.addCard({
				cardList: [{
					cardId: cardId,
					cardExt: res.cardExt
				}], // 需要添加的卡券列表，cardExt内的签名使用公众号appid获取
				success: function (res) {
					var cardList = res.cardList; // 添加的卡券列表信息
				}
			});
		})
	},
	//领取微信会员卡
	addmembercard:function(e){
		var cardId = e.currentTarget.dataset.card_id
		$.post('coupon/getmembercardparam',{card_id:cardId},function(res){
			if(res.status==0){
				$.alert(res.msg);
				return;
			}
			wx.navigateToMiniProgram({
				appId: 'wxeb490c6f9b154ef9', // 固定为此appid，不可改动
				extraData: res.extraData, // 包括encrypt_card_id outer_str biz三个字段，须从step3中获得的链接中获取参数
				success: function() {},
				fail: function() {},
				complete: function() {}
			})
		})
	},
	give_coupon_close:function(e){
		var tourl = e.currentTarget.dataset.url;
		this.setData({give_coupon_show:false});
		$.goto(tourl);
	},
	//加入购物车
	_tocart: function (e) {
		var that = this;
		var proid = e.currentTarget.dataset.proid;
		var isrefresh = e.currentTarget.dataset.isrefresh;
		$.post('shop/getproductdetail', { id: proid }, function (res) {
			
			res.product.guigedata = JSON.parse(res.product.guigedata);
			var _ggselected = [];
			var guigedata = res.product.guigedata;
			for (var i = 0; i < guigedata.length; i++) {
				_ggselected.push(0);
			}
			var _ks = _ggselected.join(',');
			that.setData({
				_prodata: res,
				_ggselected: _ggselected,
				_ks: _ks,
				_gwcnum: 1,
				_isrefresh:isrefresh
			})
			if(res.guigelist.length <= 1 && isrefresh==1){
				that._addcart();
			}else{
				that.setData({
					_buydialogShow: true
				})
			}
		})
	},
	_buydialogChange: function (e) {
		this.setData({
			_buydialogShow: !this.data._buydialogShow
		})
	},
	//选择规格
	_ggchange: function (e) {
		var idx = e.currentTarget.dataset.idx;
		var itemk = e.currentTarget.dataset.itemk;
		var _ggselected = this.data._ggselected
		_ggselected[itemk] = idx
		var _ks = _ggselected.join(',');
		this.setData({
			_ggselected: _ggselected,
			_ks: _ks
		})
	},
	_tobuy: function () {
		var that = this;
		var _ks = that.data._ks;
		var proid = that.data._prodata.product.id;
		var ggid = that.data._prodata.guigelist[_ks].id;
		var num = that.data._gwcnum;
		var prodata = proid + ',' + ggid + ',' + num;
		$.goto('/pages/shop/buy?prodata=' + prodata);
	},
	//加入购物车操作
	_addcart: function () {
		var that = this;
		var _ks = that.data._ks;
		var num = that.data._gwcnum;
		var proid = that.data._prodata.product.id;
		var ggid = that.data._prodata.guigelist[_ks].id;
		$.post('shop/addcart', { proid: proid, ggid: ggid, num: num }, function (res) {
			setTimeout(function () {
				if (res.status == 1) {
					$.success('添加成功');
					that.setData({
						_buydialogShow: false
					})
					//console.log(that.data._isrefresh)
					if(that.data._isrefresh==1) that.onShow();
				} else {
					$.error('请重试');
				}
			}, 300);
		});
	},
	//加
	_gwcplus: function (e) {
		var _gwcnum = this.data._gwcnum + 1;
		var _ks = this.data._ks;
		if (_gwcnum > this.data._prodata.guigelist[_ks].stock) {
			//wx.showToast({title:'库存不足'})
			$.error('库存不足');
			return;
		}
		this.setData({
			_gwcnum: this.data._gwcnum + 1
		})
	},
	//减
	_gwcminus: function (e) {
		var _gwcnum = this.data._gwcnum - 1;
		if (_gwcnum <= 0) {
			return;
		}
		this.setData({
			_gwcnum: this.data._gwcnum - 1
		})
	},
	//输入
	_gwcinput: function (e) {
		var _ks = this.data._ks;
		var _gwcnum = parseInt(e.detail.value);
		if (_gwcnum < 1) return 1;
		if (_gwcnum > this.data._prodata.guigelist[_ks].stock) {
			return this.data._prodata.guigelist[_ks].stock
		}
		this.setData({
			_gwcnum: _gwcnum
		});
	}
}